package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //如何获取初始化参数（局部的初始化参数）
        //如何获取到全局的初始化参数
        int pageSize = Integer.parseInt(config.getServletContext().getInitParameter("pageSize"));
        //int pageSize = Integer.parseInt(config.getInitParameter("pageSize"));
        System.out.println(pageSize);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 服务器端向客户端响应的内容类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        // 设置客户端向服务器端发送请求的编码格式
        req.setCharacterEncoding("utf-8");
        //2. 在浏览器页面中输出内容
        PrintWriter out = resp.getWriter();
        //3. 获取请求参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //4.将获取到的请求参数封装到Guestbook对象中
        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        Date date = new Date(); //需要将日期类型转换为String类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedtime(simpleDateFormat.format(date));
        //5.调用业务层的方法
        GuestbookService service = new GuestbookServiceImpl();
        boolean isRight = service.addGuestbook(gb);
        if(isRight) {
            //out.println("<a href='get'>view all guestbook</a>");
            //转发资源（从AddMessageServlet转发到GetMessageServlet）
            req.getRequestDispatcher("get").forward(req,resp);
//            resp.sendRedirect("http://www.baidu.com");//重定向
        }else {
            out.println("add error......");
        }

    }
}
